package com.alinesno.cloud.initializr.starter.gateway.rest;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alinesno.cloud.common.core.constants.SpringInstanceScope;
import com.alinesno.cloud.common.facade.constants.FieldConstants;
import com.alinesno.cloud.common.facade.response.AjaxResult;
import com.alinesno.cloud.initializr.starter.codegen.service.IGenTableService;
import com.alinesno.cloud.initializr.starter.constants.PackageTypeEnums;
import com.alinesno.cloud.initializr.starter.entity.BuildApplicationTemplatesEntity;
import com.alinesno.cloud.initializr.starter.entity.BuildGitEntity;
import com.alinesno.cloud.initializr.starter.entity.InitializrBootVersionEntity;
import com.alinesno.cloud.initializr.starter.entity.ProjectInfoEntity;
import com.alinesno.cloud.initializr.starter.enums.GitRepositoryEnum;
import com.alinesno.cloud.initializr.starter.gateway.dto.TemplateProjectDto;
import com.alinesno.cloud.initializr.starter.gateway.rest.gen.GenBaseRest;
import com.alinesno.cloud.initializr.starter.seedgen.bean.ProjectInfoDto;
import com.alinesno.cloud.initializr.starter.service.IBuildApplicationTemplatesService;
import com.alinesno.cloud.initializr.starter.service.IBuildGitService;
import com.alinesno.cloud.initializr.starter.service.IBuildProjectInfoService;
import com.alinesno.cloud.initializr.starter.service.IInitializrBootVersionService;
import com.alinesno.cloud.initializr.starter.service.IStaticService;
import com.alinesno.cloud.rest.gateway.adapter.security.CurrentAccountJwt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.ObjectId;

/**
 * 项目控制层
 *
 * @author WeiXiaoJin
 * @since 2021年1月1日 上午11:12:06
 */
@RestController
@Scope(SpringInstanceScope.PROTOTYPE)
@RequestMapping("com/alinesno/cloud/initializr/initiallizrSeed")
public class InitializrSeedRest extends GenBaseRest {

    // 日志记录
    private static final Logger log = LoggerFactory.getLogger(InitializrSeedRest.class);

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IBuildGitService buildGitService;

    @Autowired
    private IBuildProjectInfoService projectInfoService;

    @Autowired
    private IBuildApplicationTemplatesService templateService;

    @Autowired
    private IStaticService staticService;
    @Autowired
    private IInitializrBootVersionService bootVersionService;

    /**
     * 生成工程并上传gitlab
     *
     * @param response
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadGitProject")
    public AjaxResult uploadGitProject(HttpServletRequest request, @RequestBody ProjectInfoDto dto) {
        log.debug("GitProjectDto = " + dto);
        
//        BuildGitEntity e = buildGitService.findById(dto.getProjectId()) ;
     
       dto.setOperatorId(CurrentAccountJwt.getUserId());
       ProjectInfoEntity projectInfoEntity= null ; // projectInfoService.halfSave(dto);
       
		String templateId = dto.getTemplateId();
		if (StringUtils.isNotBlank(templateId)) {
			projectInfoEntity = projectInfoService.uploadGitProject(dto, templateId);
			log.debug("projectInfoEntity = {}", projectInfoEntity);
		} else {
			
			// 上传到gitlab
			if(GitRepositoryEnum.GITLAB.getName().equals(dto.getGitType())){
				
				projectInfoEntity = projectInfoService.uploadGitProject(dto); 
				log.debug("projectInfoEntity = {}", projectInfoEntity );
				
			} else if(GitRepositoryEnum.GITEE.getName().equals(dto.getGitType())){
		
				projectInfoEntity = projectInfoService.uploadGiteeProject(dto); 
				log.debug("projectInfoEntity = {}", projectInfoEntity );
				
			} else if(GitRepositoryEnum.GITEA.getName().equals(dto.getGitType())){

				projectInfoEntity = projectInfoService.uploadGiteaProject(dto); 
				log.debug("projectInfoEntity = {}", projectInfoEntity );
				
			} 
			
		}
		
        AjaxResult r = AjaxResult.success("工程生成成功.");
        r.put("projectId", projectInfoEntity.getId());
        return r;
    }

    /**
     * 生成工程并上传gitlab
     *
     * @param response
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping("/genGitProject")
    public AjaxResult genGitProject(HttpServletRequest request, @RequestBody ProjectInfoDto dto) {
        log.debug("ProjectGeneratorDto = " + dto.toString());

        ProjectInfoEntity e = new ProjectInfoEntity();
        BeanUtil.copyProperties(dto, e);
        boolean isSave = projectInfoService.save(e);

        return isSave ? AjaxResult.success("工程生成成功.", e.getId()) : AjaxResult.error();
    }

    /**
     * 生成模板工程
     *
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/generatorTemplateProject")
    public AjaxResult generatorTemplateProject(HttpServletRequest request, @RequestBody TemplateProjectDto dto) {
        log.debug("ProjectGeneratorDto = " + dto.toString());

        ProjectInfoEntity e = new ProjectInfoEntity();
        BeanUtil.copyProperties(dto, e);
        boolean isSave = projectInfoService.save(e);

        return isSave ? AjaxResult.success("工程生成成功.", e.getId()) : AjaxResult.error();
    }

    /**
     * 种子工程下载
     *
     * @param response
     * @param dto
     * @throws IOException
     */
    @GetMapping("/generatorSeedDownload")
    public void generatorSeedDownload(HttpServletRequest request, HttpServletResponse response, ProjectInfoDto info) throws IOException {

        log.debug("ProjectGeneratorDto = " + info);

        byte[] data = null;

        if (PackageTypeEnums.MAVEN.value().equals(info.getPackageType())) {
            data = genTableService.generatorSeed(info);
        } else if (PackageTypeEnums.NPM.value().equals(info.getPackageType())) {
            data = genTableService.generatorNpmSeed(info);
        }

        // 应用生成统计+1
        staticService.addGenAppCount();

        genCode(response, data, info.getArtifactId(), null);
    }

    /**
     * 获取可用的git基线地址
     */
    @GetMapping("/getSvnList")
    public AjaxResult getSvnList() {
    
    	QueryWrapper<BuildGitEntity> wrapper = new QueryWrapper<BuildGitEntity>() ; 
    	wrapper.eq(FieldConstants.OPERATOR_ID, CurrentAccountJwt.getUserId()) ;
    	
        List<BuildGitEntity> list = buildGitService.list(wrapper);
        
//        List<GitDto> gitList = new ArrayList<GitDto>();
//
//        for (BuildGitEntity e : list) {
//
//            GitDto g = new GitDto();
//
//            g.setIcon(e.getGitIcon());
//            g.setName(e.getGitName());
//            g.setNamespace(e.getGitNamespace());
//            g.setGitDesc(e.getFieldProp()) ;
//
//            gitList.add(g);
//        }

        return AjaxResult.success(list);
    }

    /**
     * 数据预览
     *
     * @return
     */
    @GetMapping("/preview")
    public AjaxResult preview() {

        return AjaxResult.success();
    }

    /**
     * 生成项目唯一标识
     *
     * @return
     */
    @GetMapping("/genProjectCode/{projectCode}")
    public AjaxResult genProjectCode(@PathVariable("projectCode") String projectCode) {

        List<ProjectInfoEntity> e = projectInfoService.queryProjectInfoByCode(projectCode);

        return AjaxResult.success(e.size());
    }

    @GetMapping("/bootVersions")
    public AjaxResult bootVersionList() {
        List<InitializrBootVersionEntity> all = bootVersionService.findAll();
        return AjaxResult.success("操作成功", all);
    }

    /**
     * 初始化
     *
     * @return
     */
    @GetMapping("/initSeedInfo")
    public AjaxResult initSeedInfo() {
        AjaxResult r = AjaxResult.success();

        // 获取公共组件
        QueryWrapper<BuildApplicationTemplatesEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_type", "component");
        List<BuildApplicationTemplatesEntity> templates = templateService.list(queryWrapper);

        r.put("templates", templates);

        // 初始化唯一域名
        String domain = ObjectId.next();
        r.put("domain", domain);

        return r;
    }

}
